package org.wzl.todolisthelper.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.wzl.todolisthelper.utils.JsonWrapperUtil;
import org.wzl.todolisthelper.utils.Resp;

import java.util.Objects;

/**
 * 全局异常处理
 * @author 卫志龙
 * @version 1.0
 * @date 2024/12/29 10:34
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    private static final ObjectMapper objectMapper = JsonWrapperUtil.objectMapper;

    @ExceptionHandler(Exception.class)
    public String handle(Exception ex, WebRequest request) {
        String json;
        try {
            json = objectMapper.writeValueAsString(Resp.fail("服务器出错"));
        } catch (JsonProcessingException e) {
            log.error("服务器出错",e);
            throw new RuntimeException(e);
        }
        return json;
    }

    @ExceptionHandler(BizException.class)
    public String bizHandle(BizException ex, WebRequest request) {
        String json;
        try {
            json = objectMapper.writeValueAsString(Resp.fail(ex.getMessage()));
        } catch (JsonProcessingException e) {
            log.error("业务报错",e);
            throw new RuntimeException(e);
        }
        return json;
    }

    @ExceptionHandler(NotLoginException.class)
    public String notLoginHandle(NotLoginException ex, WebRequest request) {
        String json;
        try {
            json = objectMapper.writeValueAsString(Resp.fail("token失效或缺失", 501));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException ex, WebRequest request) {
        String json;
        try {
            json = objectMapper.writeValueAsString(Resp.fail(Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage()));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

}
